import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:table_calendar/table_calendar.dart';

import '../../controllers/history_controller.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_text_styles.dart';
import '../../core/constants/app_constants.dart';
import '../../core/constants/emotion_constants.dart';
import '../../core/utils/app_utils.dart';
import '../../data/models/emotion_record.dart';
import '../layouts/main_layout.dart';
import '../widgets/emotion_record_card.dart';

/// 历史页面 - 用于查看历史情绪记录
/// History Page - For viewing historical emotion records
class HistoryPage extends GetView<HistoryController> {
  const HistoryPage({super.key});

  @override
  Widget build(BuildContext context) {
    return MainLayout(
      currentIndex: 1,
      child: Scaffold(
        appBar: AppBar(
          title: Text('历史记录'),
          actions: [
            // 视图切换按钮 / View toggle button
            Obx(() => IconButton(
              onPressed: controller.toggleViewMode,
              icon: Icon(
                controller.isCalendarView 
                    ? Icons.list 
                    : Icons.calendar_month,
                color: AppColors.primary,
              ),
              tooltip: controller.isCalendarView ? '列表视图' : '日历视图',
            )),
            
            // 搜索按钮 / Search button
            IconButton(
              onPressed: () => _showSearchDialog(context),
              icon: Icon(
                Icons.search,
                color: AppColors.primary,
              ),
              tooltip: '搜索记录',
            ),
          ],
        ),
        body: Obx(() => controller.isLoading
            ? const Center(child: CircularProgressIndicator())
            : controller.isCalendarView
                ? _buildCalendarView(context)
                : _buildListView(context)),
      ),
    );
  }

  /// 构建日历视图
  /// Build calendar view
  Widget _buildCalendarView(BuildContext context) {
    return Column(
      children: [
        // 日历组件 / Calendar component
        Flexible(
          flex: 1,
          child: Container(
            constraints: BoxConstraints(
              maxHeight: MediaQuery.of(context).size.height * 0.4,
            ),
            margin: EdgeInsets.symmetric(
              horizontal: AppConstants.paddingMedium.w,
              vertical: AppConstants.paddingSmall.h,
            ),
            decoration: BoxDecoration(
              color: AppColors.surface,
              borderRadius: BorderRadius.circular(AppConstants.radiusLarge.r),
              boxShadow: [
                BoxShadow(
                  color: AppColors.shadow.withOpacity(0.1),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Padding(
              padding: EdgeInsets.symmetric(
                horizontal: AppConstants.paddingSmall.w,
                vertical: AppConstants.paddingSmall.h,
              ),
              child: Obx(() => TableCalendar<EmotionRecord>(
                firstDay: DateTime.utc(2020, 1, 1),
                lastDay: DateTime.utc(2030, 12, 31),
                focusedDay: controller.focusedDay,
                selectedDayPredicate: (day) {
                  return isSameDay(controller.selectedDay, day);
                },
                calendarFormat: controller.calendarFormat,
                eventLoader: controller.getEventsForDay,
                startingDayOfWeek: StartingDayOfWeek.monday,
                availableGestures: AvailableGestures.all,
                
                // 日历样式配置 / Calendar style configuration
                calendarStyle: CalendarStyle(
                  outsideDaysVisible: false,
                  canMarkersOverflow: false,
                  markersMaxCount: 3,
                  cellMargin: EdgeInsets.all(2.r),
                  cellPadding: EdgeInsets.all(1.r),
                  
                  // 周末样式 / Weekend style
                  weekendTextStyle: AppTextStyles.bodySmall.copyWith(
                    color: AppColors.error,
                  ),
                  
                  // 假日样式 / Holiday style
                  holidayTextStyle: AppTextStyles.bodySmall.copyWith(
                    color: AppColors.error,
                  ),
                  
                  // 默认文本样式 / Default text style
                  defaultTextStyle: AppTextStyles.bodySmall,
                  
                  // 选中日期样式 / Selected day style
                  selectedDecoration: BoxDecoration(
                    color: AppColors.primary,
                    shape: BoxShape.circle,
                  ),
                  selectedTextStyle: AppTextStyles.bodySmall.copyWith(
                    color: AppColors.onPrimary,
                    fontWeight: FontWeight.bold,
                  ),
                  
                  // 今日样式 / Today style
                  todayDecoration: BoxDecoration(
                    color: AppColors.primary.withOpacity(0.3),
                    shape: BoxShape.circle,
                  ),
                  todayTextStyle: AppTextStyles.bodySmall.copyWith(
                    color: AppColors.primary,
                    fontWeight: FontWeight.bold,
                  ),
                  
                  // 标记样式 / Marker style
                  markerDecoration: BoxDecoration(
                    color: AppColors.secondary,
                    shape: BoxShape.circle,
                  ),
                  markerMargin: EdgeInsets.symmetric(
                    horizontal: 0.5.w,
                    vertical: 0.5.h,
                  ),
                  markerSize: 4.r,
                ),
                
                // 头部样式配置 / Header style configuration
                headerStyle: HeaderStyle(
                  formatButtonVisible: true,
                  titleCentered: true,
                  formatButtonShowsNext: false,
                  headerPadding: EdgeInsets.symmetric(
                    vertical: AppConstants.paddingSmall.h,
                  ),
                  formatButtonDecoration: BoxDecoration(
                    color: AppColors.primary,
                    borderRadius: BorderRadius.circular(AppConstants.radiusSmall.r),
                  ),
                  formatButtonTextStyle: AppTextStyles.bodySmall.copyWith(
                    color: AppColors.onPrimary,
                    fontSize: 10.sp,
                  ),
                  leftChevronIcon: Icon(
                    Icons.chevron_left,
                    color: AppColors.primary,
                    size: 18.sp,
                  ),
                  rightChevronIcon: Icon(
                    Icons.chevron_right,
                    color: AppColors.primary,
                    size: 18.sp,
                  ),
                  titleTextStyle: AppTextStyles.titleSmall.copyWith(
                    color: AppColors.textPrimary,
                  ),
                ),
                
                // 星期标题样式 / Days of week style
                daysOfWeekStyle: DaysOfWeekStyle(
                  weekdayStyle: AppTextStyles.bodySmall.copyWith(
                    color: AppColors.textSecondary,
                  ),
                  weekendStyle: AppTextStyles.bodySmall.copyWith(
                    color: AppColors.error,
                  ),
                ),
                
                // 事件回调 / Event callbacks
                onDaySelected: controller.onDaySelected,
                onFormatChanged: controller.onFormatChanged,
                onPageChanged: controller.onPageChanged,
                
                // 标记构建器 / Marker builder
                calendarBuilders: CalendarBuilders(
                  markerBuilder: (context, day, events) {
                    if (events.isEmpty) return null;
                    
                    return Positioned(
                      bottom: 1,
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: events.take(3).map((event) {
                          final record = event as EmotionRecord;
                          return Container(
                            margin: EdgeInsets.symmetric(horizontal: 0.3.w),
                            width: 4.r,
                            height: 4.r,
                            decoration: BoxDecoration(
                              color: EmotionConstants.getEmotionColor(record.emotionType),
                              shape: BoxShape.circle,
                            ),
                          );
                        }).toList(),
                      ),
                    );
                  },
                ),
              )),
            ),
          ),
        ),
        
        // 选中日期的记录列表 / Records list for selected date
        // 使用Expanded确保记录列表占用剩余空间
        // Use Expanded to ensure records list takes remaining space
        Expanded(
          child: Obx(() => _buildSelectedDayRecords()),
        ),
      ],
    );
  }

  /// 构建列表视图
  /// Build list view
  Widget _buildListView(BuildContext context) {
    return Column(
      children: [
        // 筛选器 / Filters
        _buildFilters(),
        
        // 记录列表 / Records list
        Expanded(
          child: Obx(() => _buildRecordsList()),
        ),
      ],
    );
  }

  /// 构建筛选器
  /// Build filters
  Widget _buildFilters() {
    return Container(
      margin: EdgeInsets.all(16.w),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '筛选条件',
            style: AppTextStyles.titleSmall.copyWith(
              color: AppColors.textPrimary,
            ),
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          
          // 情绪类型筛选 / Emotion type filter
          Wrap(
            spacing: AppConstants.spacingSmall,
            runSpacing: AppConstants.spacingSmall,
            children: [
              Obx(() => _buildFilterChip(
                label: '全部',
                isSelected: controller.selectedEmotionFilter.isEmpty,
                onTap: () => controller.setEmotionFilter(<EmotionType>{}),
              )),
              ...EmotionType.values.map((emotionType) {
                final emotionTypeString = emotionType.value;
                final emotionLabel = EmotionConstants.getEmotionLabel(emotionTypeString);
                final emotionEmoji = EmotionConstants.getEmotionEmoji(emotionTypeString);
                return Obx(() => _buildFilterChip(
                  label: '$emotionEmoji $emotionLabel',
                  isSelected: controller.selectedEmotionFilter.contains(emotionType),
                  onTap: () => controller.setEmotionFilter({emotionType}),
                ));
              }).toList(),
            ],
          ),
          
          const SizedBox(height: AppConstants.spacingMedium),
          
          // 时间范围筛选 / Time range filter
          Row(
            children: [
              Expanded(
                child: Obx(() => _buildFilterChip(
                  label: '最近7天',
                  isSelected: controller.selectedTimeFilter == 'week',
                  onTap: () => controller.setTimeFilter('week'),
                )),
              ),
              const SizedBox(width: AppConstants.spacingSmall),
              Expanded(
                child: Obx(() => _buildFilterChip(
                  label: '最近30天',
                  isSelected: controller.selectedTimeFilter == 'month',
                  onTap: () => controller.setTimeFilter('month'),
                )),
              ),
              const SizedBox(width: AppConstants.spacingSmall),
              Expanded(
                child: Obx(() => _buildFilterChip(
                  label: '全部',
                  isSelected: controller.selectedTimeFilter == 'all',
                  onTap: () => controller.setTimeFilter('all'),
                )),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建筛选芯片
  /// Build filter chip
  Widget _buildFilterChip({
    required String label,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: AppConstants.paddingMedium,
          vertical: AppConstants.paddingSmall,
        ),
        decoration: BoxDecoration(
          color: isSelected 
              ? AppColors.primary 
              : AppColors.background,
          borderRadius: BorderRadius.circular(AppConstants.radiusLarge),
          border: Border.all(
            color: isSelected 
                ? AppColors.primary 
                : AppColors.border,
          ),
        ),
        child: Text(
          label,
          style: AppTextStyles.bodySmall.copyWith(
            color: isSelected 
                ? AppColors.onPrimary 
                : AppColors.textPrimary,
          ),
        ),
      ),
    );
  }

  /// 构建选中日期的记录
  /// Build records for selected date
  Widget _buildSelectedDayRecords() {
    final records = controller.getRecordsForSelectedDay();
    
    if (records.isEmpty) {
      return Container(
        margin: const EdgeInsets.all(AppConstants.paddingMedium),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.event_note,
              size: 64,
              color: AppColors.textSecondary,
            ),
            const SizedBox(height: AppConstants.spacingMedium),
            Text(
              '这一天没有记录',
              style: AppTextStyles.titleMedium.copyWith(
                color: AppColors.textSecondary,
              ),
            ),
            const SizedBox(height: AppConstants.spacingSmall),
            Text(
              AppUtils.formatDate(controller.selectedDay),
              style: AppTextStyles.bodyMedium.copyWith(
                color: AppColors.textSecondary,
              ),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      itemCount: records.length,
      itemBuilder: (context, index) {
        final record = records[index];
        return Container(
          margin: const EdgeInsets.only(bottom: AppConstants.spacingMedium),
          child: EmotionRecordCard(
            record: record,
            onTap: () => controller.goToRecordDetail(record.id),
          ),
        );
      },
    );
  }

  /// 构建记录列表
  /// Build records list
  Widget _buildRecordsList() {
    final records = controller.filteredRecords;
    
    if (records.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.search_off,
              size: 64,
              color: AppColors.textSecondary,
            ),
            const SizedBox(height: AppConstants.spacingMedium),
            Text(
              '没有找到匹配的记录',
              style: AppTextStyles.titleMedium.copyWith(
                color: AppColors.textSecondary,
              ),
            ),
            const SizedBox(height: AppConstants.spacingSmall),
            Text(
              '尝试调整筛选条件',
              style: AppTextStyles.bodyMedium.copyWith(
                color: AppColors.textSecondary,
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: controller.refreshRecords,
      color: AppColors.primary,
      child: ListView.builder(
        padding: const EdgeInsets.all(AppConstants.paddingMedium),
        itemCount: records.length,
        itemBuilder: (context, index) {
          final record = records[index];
          return Container(
            margin: const EdgeInsets.only(bottom: AppConstants.spacingMedium),
            child: EmotionRecordCard(
              record: record,
              onTap: () => controller.goToRecordDetail(record.id),
              showDate: true,
            ),
          );
        },
      ),
    );
  }

  /// 显示搜索对话框
  /// Show search dialog
  void _showSearchDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(
          '搜索记录',
          style: AppTextStyles.titleMedium,
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: controller.searchController,
              decoration: InputDecoration(
                hintText: '输入关键词搜索日记内容或标签',
                hintStyle: AppTextStyles.bodyMedium.copyWith(
                  color: AppColors.textSecondary,
                ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                  borderSide: BorderSide(color: AppColors.border),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                  borderSide: BorderSide(color: AppColors.border),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                  borderSide: BorderSide(color: AppColors.primary, width: 2),
                ),
                prefixIcon: Icon(
                  Icons.search,
                  color: AppColors.textSecondary,
                ),
              ),
              style: AppTextStyles.bodyMedium,
              autofocus: true,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              controller.clearSearch();
              Navigator.of(context).pop();
            },
            child: Text(
              '清除',
              style: AppTextStyles.button.copyWith(
                color: AppColors.textSecondary,
              ),
            ),
          ),
          TextButton(
            onPressed: () {
              controller.searchRecords();
              Navigator.of(context).pop();
            },
            child: Text(
              '搜索',
              style: AppTextStyles.button.copyWith(
                color: AppColors.primary,
              ),
            ),
          ),
        ],
      ),
    );
  }
}